define([ "common", "wizard", "globalsettings" ],
    function($, wizard) {
      try {
        function Service() {
        }

        Service.BASE_URL = ".";
        Service.SERV_URL = "http://localhost:8080/shop"
        Service.SERV_IMGURL="http://gegewu.net.cn:8080"
        
        Service.loadServImg = function(key, onload) {

            var res = window.imgs[key];
            if (!res) {
              res = new Image();
              
              if(!onload){
              	onload=function(){
              		this.loaded=true;
              	}
              }
              if (onload) {
                res.onload = onload;
              }
              window.imgs[key] = res;
              if (key == null || key == undefined || key == "null") {
                return res;
              }
              if (key.indexOf("http") == 0) {
                res.src = key;
              } else {
                res.src = Service.SERV_IMGURL + "/imgs/" + key;
              }
            }
            return res;
          }
        	
        	
        Service.loadImg = function(key, onload) {

          var res = window.imgs[key];
          if (!res) {
            res = new Image();
            
            if(!onload){
            	onload=function(){
            		this.loaded=true;
            	}
            }
            if (onload) {
              res.onload = onload;
            }
            window.imgs[key] = res;
            if (key == null || key == undefined || key == "null") {
              return res;
            }
            if (key.indexOf("http") == 0) {
              res.src = key;
            } else {
              res.src = Service.BASE_URL + "/img/" + key
                  + (key.indexOf(".") > 0 ? "" : ".png");
            }
          }
          return res;
        }

        Service.isBlankStr = function(str) {
          var res = false;
          res = (str == null || str == undefined || str == "" || str == "null"
              || str == "undefined" || (str.trim && str.trim() == ""));
          return res;
        };

        Service.setCurUser = Service.saveUser = function(user) {
          storage._umi_user = JSON.stringify(user);
        }

        Service.getCurUser = function() {
          var str_user = storage._umi_user;
          if (Service.isBlankStr(str_user)) {
            return null;
          }
          return JSON.parse(storage._umi_user);
        }

        Service.takeAPic = function(bizObject, eventType, width, height) {
          var res = "";
          navigator.notification.confirm('从哪里获得图片？', function(button) {
            // console.log(button)
            if (button == 1) {
              var opts = {
                destinationType : Camera.DestinationType.DATA_URL,
                quality : 50,
                allowEdit : true,
                encodingType : Camera.EncodingType.PNG
              };
              if (width && height) {
                opts.targetWidth = width;
                opts.targetHeight = height;
              }

              navigator.camera.getPicture(
                  function onLoadImageSuccess(imageURI) {
                    // 这里的图片经过了base64编码
                    // console.log(imageURI)
                    // res = "data:image/jpeg;base64," + imageURI;
                    /*
                     * $("#getImage").attr("src", src); $("#getImage").show();
                     */
                    // console.log(imageURI);
                    $(bizObject).trigger(eventType, {
                      content : imageURI,
                      type : "image/png"
                    });
                  }, function(message) {
                    navigator.notification.alert("拍照失败，原因：" + message, null,
                        "警告");
                  }, opts);

            } else {
              var opts = {
                destinationType : Camera.DestinationType.FILE_URI,
                sourceType : Camera.PictureSourceType.PHOTOLIBRARY,
                quality : 50,
                allowEdit : true
              };
              if (width && height) {
                opts.targetWidth = width;
                opts.targetHeight = height;
              }

              // 获取本地图片并显示在屏幕
              navigator.camera.getPicture(
                  function onLoadImageSuccess(imageURI) {
                    // 这里的图片经过了base64编码
                    // res = "data:image/jpeg;base64," +
                    // Service.readDataUrl(imageURI);
                    Service.readDataUrl(imageURI, bizObject, eventType);
                    /*
                     * $("#getImage").attr("src", src); $("#getImage").show();
                     */
                    console.log(res);
                  }, function(message) {
                    navigator.notification.alert("拍照失败，原因：" + message, null,
                        "警告", "确定");
                  }, opts);
            }
          }, '选择图片', '拍照,相册');
          return res;

        }

        Service.savePageParam = function(obj) {
          storage._umi_page_param = JSON.stringify(obj);
        }
        Service.loadPageParam = function() {
          var param = storage._umi_page_param;
          // console.log("param:"+param);
          storage._umi_page_param = "";
          if (Service.isBlankStr(param)) {
            return null;
          } else {
            return JSON.parse(param);
          }
        }

        Service.readDataUrl = function(file, bizObject, eventType) {
          resolveLocalFileSystemURL(file, function(entry) {
            // var url = entry.toInternalURL();
            console.log(entry.file);
            entry.file(function(file) {
              console.log(file);
              try {
                var reader = new FileReader();

                reader.onloadend = function() {
                  var idx = this.result.indexOf("base64,");
                  var type = this.result.substr(5, idx - 6);// data:image/jpeg;base64,
                  var base64 = this.result.substr(idx + 7);
                  $(bizObject).trigger(eventType, {
                    content : base64,
                    type : type
                  })
                };
                reader.readAsDataURL(file);
              } catch (e) {
                console.log(e);
              }
            }, function() {
              console.log("read file error.")
            });
          });

          /*
           * if(window.FileReader) { try{ console.log(1); var fr = new
           * FileReader(); console.log(2); fr.onload=function(e){
           * console.log("haha") } fr.onloadend = function(e) {
           * console.log("hehe") //var res = e.target.result;
           * //console.log(res); }; console.log(3); console.log(file)
           * fr.readAsBinaryString(file); console.log(4); }catch(e){
           * console.log(e); } }else{ console.log("no file reader"); }
           */
        }

        Service.savePic = function(data) {
          var res = "";
          var url = Service.SERV_URL + "/fn/savePic";
          var param = data;
          $.a("postJson", url, param, function(obj) {
            res = obj;
          }, function(e, d) {
            console.log(e.responseText)
          });
          return res;
        }

        Service.logout = function() {
          console.log("logout")
          storage._umi_user = undefined;
          wizard.gotoIndex();
        }

        Service.addCommodities2ShoppingCart = function(page, commodityId,
            addOrMinus, amount) {
          console.log("called ServiceToolkit.addCommodities2ShoppingCart()");
          var $page = $(page);
          $page.trigger("whenCommit");
          var param = {
            type : addOrMinus + "",
            amount : amount + "",
            commodityId : commodityId
          };
          $.a("postJsonA", "./fn/add2Cart", param, function(res) {
            $page.trigger({
              type : "afterCommit",
              method : "updateCart",
              cart : res.data
            });
          });

        };
        
        Service.addCommodities2ShoppingCartAndGotoCart = function(page, commodityId,
            addOrMinus, amount) {
          console.log("called ServiceToolkit.addCommodities2ShoppingCartAndGotoCart()");
          
          try{
            //console.log(page);
          //var $page = $(page);
          //$page.trigger("whenCommit");
          var param = {
            type : addOrMinus + "",
            amount : amount + "",
            commodityId : commodityId
          };
          $.a("postJsonA", "./fn/add2Cart", param, function(res) {
            $("body").trigger("switchCart");
          });
          
          }catch(e){console.log(e);}
          
          console.log("called ServiceToolkit.addCommodities2ShoppingCartAndGotoCart() end");
        };

        Service.lookAtCart = function(callback) {
          console.log("call Service::lookAtCart()");
          $.a("postJsonA", "./fn/lookatShoppingCart", {}, function(res) {
            callback(res.data);
          });
        };

        Service.removeCommoditiesFromShoppingCart = function(commodityId,
            callback) {
          console.log("called Service.removeCommoditiesFromShoppingCart()");
          $.a("postJsonA", "./fn/removeFromCart", {
            commodityId : commodityId
          }, function(res) {
            callback(res.data);
          });
        }

        Service.loadAddresses = function(openId, callback) {
          console.log("call service.loadAddresses");
          $.a("postJsonA", "./fn/loadAddresses", {
            openId : openId
          }, function(res) {
            callback(res.data);
          });
        }

        Service.commitCart = function(address,wantTime, callback) {
          console.log("call service::commitCart(address,callback)");
          // console.log("address:"+JSON.stringify(address));

          $.a("postJsonA", "./fn/createNewOrder", {
            address : address
            ,wantTime:wantTime
          }, function(res) {
            var fn = callback;
            fn && $.isFunction(fn) && (function(order) {
              callback(order);
            })(res.data);
          });

        }

        /**
         * 添加地址.
         */
        Service.addAddress = function(add, callback) {
          var fn = function() {
            callback.apply(add);
          }
          $.a("postJsonA", "./fn/addAddress", add, fn, fn);
        };

        Service.loadOrderHis = function(pageStart, pageSize, callback) {
          console.log("call Service::loadOrderHis");
          $.a("postJsonA", "./fn/loadOrders", {
            page : {
              start : pageStart,
              size : pageSize
            }
          }, callback);
        }
        //zhao_f
        Service.loadOrdersByTimerType=function(pageStart,pageSize,timertype,callback){
        	console.log("call Service:: loadOrdersByTimerType");
        	$.a("postJsonA","./fn/loadOrdersByTimerType",{
        		page:{
        			start: pageStart,
        			size:pageSize
        		},
        		timertype:timertype
        	},callback);
        }
        Service.updatePayTimeOrder=function(page,timergood,callback){
        	console.log("call Service:: updatePayTimeOrder");
            var $page = $(page);
            $page.trigger("whenOpCommit");
        	$.a("postJsonA","./fn/updatePayTimeOrder",timergood,function(res){
        		$page.trigger("afterOpCommit");
        		callback(res);
        	});
        }
        Service.updatePayTimeToFinishTimeOrder=function(page,timergood,callback){
        	console.log("call Service:: updatePayTimeToFinishTimeOrder");
        	var $page = $(page);
            $page.trigger("whenOpCommit");
        	$.a("postJsonA","./fn/updatePayTimeToFinishTimeOrder",timergood,function(res){
        		$page.trigger("afterOpCommit");
        		callback(res);
        	});
        }
        Service.updateFinishTimeOrder=function(page,timergood,callback){
        	console.log("call Service:: updateFinishTimeOrder");
        	var $page = $(page);
            $page.trigger("whenOpCommit");
        	$.a("postJsonA","./fn/updateFinishTimeOrder",timergood,function(res){
        		$page.trigger("afterOpCommit");
        		callback(res);
        	});
        }
        //zhao_f end
        Service.updateAsDefaultAddress = function(address) {
          console.log("call Service::updateAsDefaultAddress(address)");
          $.a("postJsonA", "./fn/updateAsDefaultAddress", address, $.noop,
              $.noop);
        }

        Service.unuseAddress = function(address, callback) {
          console.log("call Server::unuseAddress(address)");
          $.a("postJsonA", "./fn/unuseAddress", address, function(res) {
            callback(res);
          });
        }

        Service.updateUserBaseInfo = function(baseinfo, callback) {
          console.log("call Server::updateUserBaseInfo(baseinfo,callback)");
          $.a("postJsonA", "./fn/updateUserBaseInfo", baseinfo, function(res) {
            callback(res);
          });
        }

        Service.payAnOrder = function(order, callback) {

          $.a("postJson", "./fn/payAnOrder", order, function(data) {

            if (data.sysFlag == "zero") {
              // PageFlowToolkit.go2P15OrderHistory();

              return;
            }

            function onBridgeReady() {
              WeixinJSBridge.invoke('getBrandWCPayRequest', {
                "appId" : 'wx5c303dff15810ad4', // 公众号名称，由商户传入
                "timeStamp" : data.timeStamp, // 时间戳，自1970年以来的秒数
                "nonceStr" : data.nonceStr, // 随机串
                "package" : data["package"],
                "signType" : data.signType, // 微信签名方式：
                "paySign" : data.paySign
              // 微信签名
              }, function(res) {
                // $.a("postJson", "./fn/printPostInLog", res,function(){});
                // 使用以上方式判断前端返回,微信团队郑重提示：
                // res.err_msg将在用户支付成功后返回 ok，
                // 但并不保证它绝对可靠。
                // get_brand_wcpay_request:ok
                // PageFlowToolkit.go2P15OrderHistory();
                callback();
              });
            }
            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady,
                    false);
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
              }
            } else {
              onBridgeReady();
            }

          }, function(e, code) {
            alert("error:" + e.responseText + ";code:" + code)
          });
        }
        //获得所有Commodities
        Service.getCommoditiesAll = function(callback){
        	$.a("postJsonA","./fn/LoadCommoditiesAll",{},function(res){
        		callback(res);
        	});
        }

        window.serv = Service;

        return Service;

      } catch (e) {
        console.log(e)
      }
    });
